package com.cskaoyan.controller.wx;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.User;
import com.cskaoyan.bean.vo.KeywordAndSearchHistoryVo;
import com.cskaoyan.exception.UnLoginException;
import com.cskaoyan.service.SearchService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Description
 * 小程序商品搜索
 *
 * @author Zhangfei
 * @date Created on 2021/10/21
 */

@RestController
@RequestMapping("/wx/search")
public class WXSearchController {

    @Autowired
    SearchService searchService;

    /**
     * 查询默认关键词，热点关键词
     * 还要搜索历史
     *
     * @return
     */
    @GetMapping("/index")
    public BaseRespVo index() {
        KeywordAndSearchHistoryVo index = searchService.index();
        return BaseRespVo.ok(index);
    }

    /**
     * 根据搜索返回关键词
     *
     * @param keyword
     * @return
     */
    @GetMapping("/helper")
    public BaseRespVo helper(String keyword) {
        List<String> list = searchService.helper(keyword);
        return BaseRespVo.ok(list);
    }


    @PostMapping("clearhitory")
    public BaseRespVo clearhistory() throws UnLoginException {
        //获得登陆主体
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if(user==null) throw new UnLoginException("未登录,请登录");
        //传入id
        Integer userId = user.getId();
        Integer count = searchService.clearhistory(userId);
        //根据结果响应出去
        if (count != 0) {
            return BaseRespVo.ok();
        }
        return BaseRespVo.fail("删除失败");
    }

}
